import subprocess
import sys
import os

def build_with_uv():
    """使用uv环境打包"""
    
    print("正在使用uv环境打包...")
    
    # 首先确保在uv环境中安装PyInstaller
    print("安装PyInstaller到uv环境...")
    result = subprocess.run(["uv", "pip", "install", "pyinstaller"], 
                          capture_output=True, text=True)
    if result.returncode != 0:
        print(f"安装PyInstaller失败: {result.stderr}")
        return False
    
    # 检查PyQt6是否可用
    print("检查PyQt6...")
    result = subprocess.run(["uv", "run", "python", "-c", "import PyQt6; print('PyQt6 OK')"], 
                          capture_output=True, text=True)
    if result.returncode != 0:
        print(f"PyQt6不可用: {result.stderr}")
        return False
    else:
        print(result.stdout)
    
    # 使用uv run执行PyInstaller
    cmd = [
        "uv", "run", "pyinstaller",
        "--onefile",
        "--windowed",
        "--name=CartoonViewer",
        "--clean",
        "--noconfirm",
        "main.py"
    ]
    
    # 添加图标
    if os.path.exists("icon.ico"):
        cmd.extend(["--icon=icon.ico"])
    
    # 添加数据文件
    if os.path.exists("config.ini"):
        cmd.extend(["--add-data=config.ini;."])
    
    print(f"执行命令: {' '.join(cmd)}")
    
    # 执行打包
    result = subprocess.run(cmd)
    
    if result.returncode == 0:
        print("打包成功！")
        if os.path.exists("dist/CartoonViewer.exe"):
            print("可执行文件已生成: dist/CartoonViewer.exe")
            # 显示文件大小
            size = os.path.getsize("dist/CartoonViewer.exe")
            print(f"文件大小: {size / (1024*1024):.1f} MB")
        return True
    else:
        print("打包失败")
        return False

if __name__ == "__main__":
    build_with_uv()